package geektime.spring.springbucks.service;

import com.github.pagehelper.PageInfo;
import geektime.spring.springbucks.dao.CoffeeDao;
import geektime.spring.springbucks.model.Coffee;
import geektime.spring.springbucks.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;


@Slf4j
@Service
public class CoffeeService {

    private static final String CACHE = "springbucks-coffee";

    @Autowired
    private CoffeeDao coffeeDao;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RedisUtil redisUtil;
    // @Autowired
    // private RedisTemplate<String, Coffee> redisTemplate;

    // public Optional<Coffee> findOneCoffee(String name) {
    //     ExampleMatcher matcher = ExampleMatcher.matching()
    //             .withMatcher("name", exact().ignoreCase());
    //     Optional<Coffee> coffee = coffeeRepository.findOne(
    //             Example.of(Coffee.builder().name(name).build(), matcher));
    //     log.info("Coffee Found: {}", coffee);
    //     return coffee;
    // }
    public List<Coffee> allCoffees(){
        log.info("Coffee Found: {}", coffeeDao);
        return coffeeDao.allCoffees();
    }

    public int updateCoffeeByName(Coffee coffee){
        log.info("Coffee Found: {}", coffee);
        return coffeeDao.Update(coffee);
    }

    // @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public int updateCoffeeByNameTextException(Coffee coffee) throws Exception{
        log.info("Exception before: {}", findCoffeeByName(coffee));
        coffeeDao.Update(coffee);
        log.info("Exception after: {}", findCoffeeByName(coffee));
        throw new Exception("人工抛异常");
    }

    public Coffee findCoffeeByName(Coffee coffee){
        Coffee coffeeByName = coffeeDao.findCoffeeByName(coffee);
        redisUtil.hashSet(CACHE, "name", coffeeByName);
        return coffeeByName;
    }

    public PageInfo<Coffee> findAllWithParam(String curPage, String pageNum){
        log.info("Coffee Found: {}", coffeeDao);
        int curPageIn = Integer.parseInt(curPage);
        int pageNumIn = Integer.parseInt(pageNum);
        List<Coffee> allWithParam = coffeeDao.findAllWithParam(curPageIn, pageNumIn);
        log.info("分页数据列表: {}", allWithParam);
        PageInfo<Coffee> pi = new PageInfo<Coffee>(allWithParam);
        return pi;
    }


}
